import java.util.concurrent.atomic.AtomicInteger;

public class CASExample {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        // 初始值为0
        System.out.println("初始值：" + counter.get());

        // 假设同时有多个线程执行增加操作
        Runnable task = () -> {
            for (int i = 0; i < 10; i++) {
                int oldValue, newValue;
                do {
                    // 读取当前值
                    oldValue = counter.get();
                    // 计算新值
                    newValue = oldValue + 1;
                    // 使用CAS进行比较并交换
                } while (!counter.compareAndSet(oldValue, newValue)); // 如果旧值等于当前值，则更新为新值
            }
        };

        // 创建多个线程执行增加操作
        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(task);
            threads[i].start();
        }

        // 等待所有线程执行完毕
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 输出最终结果
        System.out.println("最终值：" + counter.get());
    }
}
